<template>
  <div class="home">
    <!-- 外层容器。当子元素中包含 <el-header> 或 <el-footer> 时，全部子元素会垂直上下排列，否则会水平左右排列。-->
    <el-container id="containerA">
      <el-header style="padding: 0; display: flex;flex-direction: row;">
        <div id="systemName" @click="toggleLeftMenusCollapse">
          XXX系统
        </div>
        <div style="flex-grow: 1;">
          <el-menu class="el-menu-demo" mode="horizontal" @select="handleSelect" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b">
            <!-- topMenus左边 -->
            <el-menu-item index="1">处理中心</el-menu-item>
            <el-submenu index="2">
              <template slot="title">我的工作台</template>
              <el-menu-item index="2-1">选项1</el-menu-item>
              <el-menu-item index="2-2">选项2</el-menu-item>
              <el-menu-item index="2-3">选项3</el-menu-item>
              <el-submenu index="2-4">
                <template slot="title">选项4</template>
                <el-menu-item index="2-4-1">选项1</el-menu-item>
                <el-menu-item index="2-4-2">选项2</el-menu-item>
                <el-menu-item index="2-4-3">选项3</el-menu-item>
              </el-submenu>
            </el-submenu>
            <el-menu-item index="3" disabled>消息中心</el-menu-item>
            <el-menu-item index="4"><a href="https://www.ele.me" target="_blank">订单管理</a></el-menu-item>
            <!-- topMenus右边 -->
            <el-menu-item index="6" style="float: right;">登出</el-menu-item>
            <el-submenu index="5" style="float: right;">
              <template slot="title">系统管理员</template>
              <el-menu-item index="5-1">个人信息</el-menu-item>
              <el-menu-item index="5-2">修改密码</el-menu-item>
            </el-submenu>
          </el-menu>
        </div>
      </el-header>
      <el-container id="containerB">
        <!-- 左边菜单 -->
        <el-menu :default-active="activeMenuId" ref="leftMenu" id="leftMenu" @select="selectMenu" :default-openeds="defaultOpeneds" :collapse="isCollapse">
          <span v-for="menu1 in menuList" :key="menu1.id" :index="menu1.id">
            <!-- 一级菜单如果有子菜单 -->
            <el-submenu v-if="menu1.pid === '-1' && menu1.haschild === 1" :index="menu1.id">
              <span slot="title">{{menu1.name}}</span>
              <span v-for="menu2 in menuList" :key="menu2.id">
                <!-- 二级菜单如果有子菜单 -->
                <el-submenu v-if="menu2.pid === menu1.id && menu2.haschild === 1" :index="menu2.id">
                  <span slot="title">{{menu2.name}}</span>
                  <span v-for="menu3 in menuList" :key="menu3.id">
                    <!-- 三级菜单暂时不考虑有子菜单 -->
                    <el-menu-item v-if="menu3.pid === menu2.id && menu3.haschild === 0" :id="`leftMenu-${menu3.id}`" :index="menu3.id" @click="addTab(menu3)">
                      {{menu3.name}}
                    </el-menu-item>
                  </span>
                </el-submenu>
                <!-- 二级菜单如果没有子菜单 -->
                <el-menu-item v-else-if="menu2.pid === menu1.id && menu2.haschild === 0" :id="`leftMenu-${menu2.id}`" :index="menu2.id" @click="addTab(menu2)">
                  {{menu2.name}}
                </el-menu-item>
              </span>
            </el-submenu>
            <!-- 一级菜单如果没有子菜单 -->
            <el-menu-item v-else-if="menu1.pid === -1 && menu1.haschild === 0" :id="`leftMenu-${menu1.id}`" :index="menu1.id" @click="addTab(menu1)">
              {{menu1.name}}
            </el-menu-item>
          </span>
        </el-menu>
        <!-- 内容部分 -->
        <el-container id="containerC">
          <el-main>
            <RightMenu :menus="rightMenu" @click="rightMenuClick" :target="'.el-tabs__nav'" />
            <el-tabs v-model="activeTabId" type="card" closable @tab-remove="removeTab" @tab-click="leftMenuClick($event)">
              <el-tab-pane v-for="(item) in tabList" :key="item.id" :name="item.id" :label="item.title">
                <span slot="label">
                  <i class="iconfont icon-dianyingpiao"></i>{{item.title}}
                </span>
              </el-tab-pane>
            </el-tabs>
            <div id="tabContent">
              <keep-alive :include="keepAliveCache">
                <router-view v-if="isRouterAlive" name="tabContent"></router-view>
              </keep-alive>
            </div>
          </el-main>
          <!-- 底部 -->
          <el-footer style="height: 20px;">
            <a target="_blank" class="ICP">由XXX提供技术支持</a>
          </el-footer>
        </el-container>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import RightMenu from '@/components/RightMenu';
import res from '@/api/sysMenu/list.json';
export default {
  name: 'Home',
  components: {
    RightMenu: RightMenu
  },
  created () {
    // TODO，获取menuList，这里可能要用同步
    // this.$http.get('http://rap2.taobao.org:38080/app/mock/257330/menu/list').then(res => {
    // });
    this.menuList = res.data;
    this.menuList.map((item) => {
      item.id = String(item.id);
      item.pid = String(item.pid);
    })
  },
  mounted () {
    // 根据路由展开leftMenus
    const menuList = this.menuList.filter(item => item.url === this.$route.path);
    if (menuList.length === 0) {
      return;
    }
    const menu = menuList[0];
    document.getElementById(`leftMenu-${menu.id}`).click();
    this.defaultOpeneds = [menu.pid]
  },
  data () {
    return {
      // 左边菜单
      activeMenuId: '',
      menuList: [],
      isCollapse: false, // 左菜单的展开和收起状态，TODO
      // tab列表
      activeTabId: '',
      tabList: [],
      defaultOpeneds: [],
      rightMenu: [
        { menuName: '刷新该菜单', icon: 'el-icon-share' },
        { menuName: '关闭该菜单', icon: 'el-icon-star-off' },
        { menuName: '关闭其他菜单', icon: 'el-icon-star-off' }
      ],
      //keep-alive缓存，比如缓存组件：sysMenu、sysRole，则keepAliveCache:'sysMenu,sysRole'
      keepAliveCache: '',
      isRouterAlive: true
    }
  },
  methods: {
    selectMenu (index, indexPath) {
      // console.log(index, indexPath)
    },
    // 切换左菜单的展开和收起状态
    toggleLeftMenusCollapse () {
      this.isCollapse = !this.isCollapse;
    },
    // 顶部的菜单选择事件
    handleSelect (key, keyPath) {
      // console.log(key, keyPath)
    },
    // 点击左边的菜单添加tab
    addTab (menu) {
      const tabs = this.tabList;
      if (tabs.filter(tab => tab.id === menu.id).length === 0) {
        // 添加tab
        tabs.push({
          id: menu.id,
          title: menu.name,
          url: menu.url
        });
      }
      // 将leftMenus焦点和当前路由转移到该tab上
      this.activeTabId = menu.id;
      this.replaceUrl(menu.url);
      //添加缓存
      if (!this.keepAliveCache) {
        this.keepAliveCache = menu.componentName;
      } else if (this.keepAliveCache.split(',').filter(item => item === menu.componentName).length === 0) {
        this.keepAliveCache += ',' + menu.componentName;
      }
    },
    // 删除tab，并且重新渲染左边的菜单
    removeTab (targetId) {
      const tabs = this.tabList;
      // 重置activeTab
      if (this.activeTabId === targetId) {
        tabs.forEach((tab, index) => {
          if (tab.id === targetId) {
            const nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              this.leftMenuClick({ name: nextTab.id });
            }
          }
        });
      }
      // 删除tab，如果已经没有tab了，则路由重置为home
      this.tabList = tabs.filter(tab => tab.id !== targetId);
      if (this.tabList.length === 0) {
        // 清除左菜单的active
        document.getElementById(`leftMenu-${this.activeTabId}`).classList.remove("is-active");
        // 重置路由
        this.refrenshContentRouter();
        this.activeTabId = "";
      }
      // 删除缓存
      const menuList = this.menuList.filter(item => item.id === targetId);
      if (menuList.length !== 0) {
        this.keepAliveCache = this.keepAliveCache.split(',').filter(item => item !== menuList[0].componentName).join(',');
      }
    },
    // 根据tabId，点击左菜单，使对应的页面变为当前显示的页面
    leftMenuClick (tab) {
      const tabId = tab.name;
      document.getElementById(`leftMenu-${tabId}`).click();
    },
    // 监听右键菜单点击
    rightMenuClick (attachTarget, menu) {
      while (!attachTarget.hasAttribute('id')) {
        let parentNode = attachTarget.parentNode;
        if (!parentNode) {
          break;
        }
        attachTarget = attachTarget.parentNode;
      }

      let tabId = attachTarget.getAttribute('id').replace('tab-', '');
      if (menu.menuName === '刷新该菜单') {
        let menuList = this.menuList.filter(item => item.id === tabId);
        if (menuList.length !== 0) {
          // 使刷新页面获得焦点
          this.leftMenuClick({ name: tabId });
          // 刷新页面
          let componentName = menuList[0].componentName;
          let oldKeepAliveCache = this.keepAliveCache;
          this.keepAliveCache = oldKeepAliveCache.split(',').filter(item => item !== componentName).join(",");
          this.reloadRouterView(() => {
            this.keepAliveCache = oldKeepAliveCache;
          });
        }
      } else if (menu.menuName === '关闭该菜单') {
        this.removeTab(tabId)
      } else if (menu.menuName === '关闭其他菜单') {
        // 根据tabId，点击左菜单，使对应的页面变为当前显示的页面
        this.leftMenuClick({ name: tabId });
        // 删除其他菜单
        this.tabList = this.tabList.filter(tab => tab.id === tabId);
        // 删除缓存
        const menuList = this.menuList.filter(item => item.id === tabId);
        if (menuList.length !== 0) {
          this.keepAliveCache = menuList[0].componentName;
        }
      }
    },
    refrenshContentRouter (activeTabId) {
      const menuList = this.menuList.filter(item => String(item.id) === String(activeTabId));
      if (!activeTabId || menuList.length === 0) {
        this.replaceUrl('/home');
      } else {
        const menu = menuList[0];
        this.replaceUrl(menu.url);
      }
    },
    replaceUrl (url) {
      if (this.$route.path !== url) {
        this.$router.replace(url);
      }
    },
    // 刷新routerView
    reloadRouterView (callback) {
      this.isRouterAlive = false
      this.$nextTick(function () {
        this.isRouterAlive = true
        callback();
      });
    }
  }
}
</script>

<!--scss：拓展css的功能，将scss转成适配所有浏览器的css-->
<!--vueCli安装并使用scss，参考博客：https://www.cnblogs.com/xsffliu/p/11043834.html-->
<!--npm install  sass-loader node-sass --save -->
<style rel="stylesheet/scss" lang="scss">
.home {
  height: 100%;
  min-width: 1000px;
  min-height: 400px;
  // 系统名称
  #systemName {
    width: 200px;
    line-height: 60px;
    background-color: rgb(84, 92, 100);
    color: white;
    text-align: center;
  }
  // home下面的大容器
  #containerA {
    height: 100%;
    > .el-header {
      height: 60px;
    }
    > #containerB {
      height: calc(100% - 60px);
      > #leftMenu {
        width: 200px;
        max-height: 100%;
        overflow-y: auto;
        .is-active.el-menu-item {
          background-color: #ecf5ff;
        }
      }
      > #containerC {
        > .el-main {
          padding: 0;
          > #tabContent {
            height: calc(100% - 56px);
            overflow: auto;
          }
        }
        > .el-footer {
          height: 20px;
          line-height: 20px;
          background-color: #eee;
          text-align: center;
          font-size: 11px;
          color: slategrey;
        }
      }
    }
  }
}
</style>
